<template>
	<div class="web_box select_none">
		<el-scrollbar
			height="100%"
			class="left_console">
			<div class="main">
				<!-- <div class="console">工作台</div> -->
				<div class="main_menu">
					<div class="title">主菜单</div>
					<div
						class="list"
						:class="{ active: main_menu_active === i.id }"
						v-for="i in main_items"
						:key="i.id"
						@click="main_menu_click(i)">
						<div class="left">
							<span
								class="iconfont font"
								:class="i.icon"></span>
							<span class="text">{{ i.name }}</span>
						</div>
					</div>
				</div>
				<div class="my_category">
					<div class="title">
						<span>我的分类</span
						><span
							class="add"
							@click="add_category"
							>+ 新建</span
						>
					</div>
					<div
						class="list"
						:class="{ active: main_menu_active === i.id }"
						v-for="i in categories"
						:key="i.id"
						@click="main_menu_click(i)">
						<div class="left">
							<span class="text">{{ i.name }}</span>
						</div>
					</div>
				</div>
				<div class="common_tags">
					<div class="title">
						<span>常用标签</span>
						<span
							class="manage"
							@click="tag_manage"
							>管理</span
						>
					</div>
					<el-popover
						v-for="i in occurrence_tags"
						:content="`使用次数：${i.occurrence_count}`"
						placement="bottom"
						:hide-after="50">
						<template #reference>
							<div
								class="tag"
								:key="i.id">
								{{ i.name }}
							</div>
						</template>
					</el-popover>
				</div>
				<!-- <div>
          			<div>手动同步数据</div>
        		</div>  -->
			</div>
		</el-scrollbar>

		<el-scrollbar
			height="100%"
			class="right_display">
			<div class="main">
				<nav class="top_navigation">
					<el-input
						v-model="search_str"
						placeholder="搜索收藏内容..."
						class="search-input">
						<template #append>
							<el-icon><Search /></el-icon>
						</template>
					</el-input>
					<div class="view-mode-buttons">
						<span
							:class="{ active: display_mode === 'grid' }"
							class="iconfont icon-grid icon_font"
							@click="display_mode_change('grid')"></span>
						<span
							:class="{ active: display_mode === 'list' }"
							class="iconfont icon-liebiao1 icon_font"
							@click="display_mode_change('list')"></span>
					</div>
					<el-select
						v-model="sort_mode"
						class="sort-select">
						<el-option
							v-for="item in options"
							:key="item.value"
							:label="item.label"
							:value="item.value" />
					</el-select>
					<div
						class="add"
						@click="add">
						新建收藏
					</div>
				</nav>
				<div class="details">
					<div class="category">{{ active_name }}</div>
					<div class="amount">共{{ filter_web_list.length }}个收藏项</div>
				</div>

				<main
					class="grid"
					v-if="display_mode === 'grid'">
					<web_grid_index
						:bookmark="i"
						:tags="tags"
						v-for="i in filter_web_list"
						:key="i.id"
						@editBookmark="edit_bookmark"
						@deleteBookmark="delete_bookmark"
						@click.stop="bookmark_click(i)"></web_grid_index>
				</main>
				<main
					class="list"
					v-if="display_mode === 'list'">
					<web_list_index
						:bookmark="i"
						:tags="tags"
						v-for="i in filter_web_list"
						:key="i.id"
						@editBookmark="edit_bookmark"
						@deleteBookmark="delete_bookmark"
						@click="bookmark_click(i)"></web_list_index>
				</main>
			</div>
		</el-scrollbar>

		<my_dialog
			title="新建收藏"
			:dialog="dialog"
			width="600"
			@sure="dialog_sure"
			@close="dialog_close">
			<el-form
				v-model="form"
				label-width="auto"
				label-position="right">
				<el-form-item
					label="网站 URL"
					prop="url">
					<el-input v-model="form.url" />
				</el-form-item>
				<el-form-item
					label="标题"
					prop="title">
					<el-input v-model="form.title" />
				</el-form-item>
				<el-form-item
					label="简介"
					prop="description">
					<el-input v-model="form.description" />
				</el-form-item>
				<el-form-item
					label="网站的预览图片"
					prop="preview_image">
					<el-input
						v-model="form.preview_image"
						placeholder="请选择或输入预览图片URL">
						<template #append
							><el-upload
								:auto-upload="false"
								:show-file-list="false"
								:on-change="file_change">
								<template #trigger>
									<el-button type="primary">选择图片</el-button>
								</template>
							</el-upload></template
						>
					</el-input>
				</el-form-item>
				<el-form-item
					label="分类"
					prop="category_id">
					<el-select
						v-model="form.category_id"
						placeholder="请选择分类!">
						<el-option
							v-for="item in categories"
							:key="item.id"
							:label="item.name"
							:value="item.id" />
					</el-select>
				</el-form-item>
				<el-form-item label="标签">
					<el-select
						v-model="form.tags"
						multiple
						collapse-tags
						collapse-tags-tooltip
						placeholder="请选择标签!">
						<el-option
							v-for="item in tags"
							:key="item.id"
							:label="item.name"
							:value="item.id" />
					</el-select>
				</el-form-item>
			</el-form>
		</my_dialog>
		<my_dialog
			title="新建分类"
			:dialog="add_category_dialog"
			width="600"
			@sure="add_category_dialog_sure"
			@close="add_category_dialog = false">
			<el-form
				v-model="add_category_form"
				label-width="auto"
				label-position="right">
				<el-form-item
					label="分类名称"
					prop="name">
					<el-input
						v-model="add_category_form.name"
						placeholder="请输入分类名称！" />
				</el-form-item>
			</el-form>
		</my_dialog>
		<my_dialog
			title="标签管理"
			:dialog="tag_manage_dialog"
			width="600"
			:is_display_footer="false"
			@close="tag_manage_dialog = false">
			<div class="tag_manage_main">
				<div class="add_tag">
					<el-input
						v-model="add_tag_form.name"
						class="tag_input"
						placeholder="请输入标签名称！" />
					<div
						class="add_tag_cilck"
						@click="add_tag">
						新增标签
					</div>
				</div>
				<el-table
					:data="tags"
					border
					current-row-key="id"
					height="240"
					style="width: 100%">
					<el-table-column
						type="index"
						width="80"
						align="center"
						label="编号" />
					<el-table-column
						prop="name"
						label="标签名称"
						align="center"
						width="300" />
					<el-table-column
						align="right"
						label="操作"
						min-width="120">
						<template #default="scope">
							<el-button
								link
								type="primary"
								size="small"
								@click="del_tag(scope.row)">
								删除
							</el-button>
							<el-button
								link
								type="primary"
								size="small"
								@click="edit_tag(scope.row)">
								编辑
							</el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>
		</my_dialog>
	</div>
</template>

<script setup>
	import { ref, computed, onBeforeMount } from "vue";
	import { useIndexStore } from "@/store/model/index";
	import { Search } from "@element-plus/icons-vue";
	import web_grid_index from "@/components/crad/web_grid_index.vue";
	import web_list_index from "@/components/crad/web_list_index.vue";
	import my_dialog from "@/components/my_dialog/index.vue";
	import { Events } from "@/utils/events_bus/index.js";
	import { my_message } from "@/utils/my_message/index.js";
	import { ElMessageBox } from "element-plus";
	import service from "@/data_base/service/main.js";

	const store = useIndexStore();
	const msg = my_message();

	const main_items = [
		{
			id: "all",
			name: "全部收藏",
			icon: "icon-diqiu",
		},
		{
			id: "recent",
			name: "最近添加",
			icon: "icon-zuijinlaifang",
		},
		{
			id: "frequent",
			name: "常用网站",
			icon: "icon-shoucang",
		},
	];
	const main_menu_active = ref(main_items[0].id);
	const active_name = ref(main_items[0].name);
	const search_str = ref("");
	const display_mode = ref("grid"); // 初始显示模式为网格
	const sort_mode = ref(1); // 初始排序模式为最新
	const options = [
		{ value: 1, label: "按添加日期" },
		{ value: 2, label: "按名称" },
		{ value: 3, label: "访问频率" },
	];
	const dialog = ref(false);
	const add_category_dialog = ref(false);
	const tag_manage_dialog = ref(false);
	const form = ref({
		url: "",
		title: "",
		description: "",
		preview_image: "",
		tags: [],
		category_id: "",
		added_date: 0,
		visit_count: 0,
	});
	const add_category_form = ref({
		name: "",
	});
	const add_tag_form = ref({
		name: "",
	});
	const web_list_all = ref([]);
	const base_url = `${store.config.domain}:${store.config.port}`;
	const flag = ref(true);
	const edit_id = ref("");
	const tags = ref([]);
	const categories = ref([]);
	const occurrence_tags = ref([]);

	onBeforeMount(async () => {
		const res = await Promise.all([
			service.web.get_web_all(),
			service.web_tags.get_all_web_tags(),
			service.web_classify.get_all_web_classify(),
			service.query.getTopTagsByOccurrenceCount(5),
		]);
		web_list_all.value = res[0].data;
		tags.value = res[1].data;
		categories.value = res[2].data;
		occurrence_tags.value = res[3].data;
	});

	const filter_web_list = computed(() => {
		let result = [...web_list_all.value];
		//分类筛选
		if (!main_items.map(i => i.id).includes(main_menu_active.value)) {
			result = result.filter(i => i.category_id === main_menu_active.value);
		}
		//最近筛选
		if (main_menu_active.value === "recent") {
			const today = new Date();
			today.setDate(today.getDate() - 10);
			const today_time = today.getTime();
			result = result.filter(i => {
				return i.added_date >= today_time;
			});
		}
		//常用筛选
		if (main_menu_active.value === "frequent") {
			result = result.filter(i => i.visit_count >= 20);
		}
		if (search_str.value) {
			const query = search_str.value.toLowerCase();
			result = result.filter(
				item =>
					item.title.toLowerCase().includes(query) ||
					item.description.toLowerCase().includes(query) ||
					// 使用 some 方法简化标签筛选逻辑
					item.tags.some(tagId => {
						const tag = tags.value.find(t => t.id === tagId);
						return tag && tag.name.toLowerCase().includes(query);
					})
			);
		}

		// 排序
		if (sort_mode.value === 1) {
			result.sort((a, b) => b.added_date - a.added_date);
		} else if (sort_mode.value === 2) {
			result.sort((a, b) => a.title.localeCompare(b.title));
		} else if (sort_mode.value === 3) {
			result.sort((a, b) => b.visit_count - a.visit_count);
		}
		return result;
	});

	const main_menu_click = i => {
		main_menu_active.value = i.id;
		active_name.value = i.name;
	};
	const display_mode_change = mode => {
		display_mode.value = mode;
	};
	const add = () => {
		flag.value = true; // 判断当前dialog是编辑还是新增，
		dialog.value = true;
	};
	const init_from = () => {
		form.value = {
			url: "",
			title: "",
			description: "",
			preview_image: "",
			tags: [],
			category_id: "",
			added_date: 0,
			visit_count: 0,
		};
	};
	const dialog_sure = async () => {
		form.value.added_date = new Date().getTime();
		if (flag.value) {
			let res = await service.web.add_web(form.value);
			if (res.code == 200) {
				web_list_all.value.push(res.data);
			} else {
				let web_list = JSON.parse(localStorage.getItem("web_list"));
				if (!web_list) {
					localStorage.setItem("web_list", JSON.stringify([form.value]));
				} else {
					web_list.push(form.value);
					localStorage.setItem("web_list", JSON.stringify(web_list));
				}
				msg.msg_warning("添加失败，已缓存该数据！");
			}
		} else {
			let res = await service.web.update_web(edit_id.value, form.value);
			if (res.code == 200) {
				web_list_all.value.forEach(item => {
					if (item.id == res.data.id) {
						for (const key in item) {
							if (Object.prototype.hasOwnProperty.call(item, key)) {
								if (key != "id") {
									item[key] = res.data[key];
								}
							}
						}
					}
				});
			}
		}
		init_from();
		dialog.value = false;
	};
	const dialog_close = () => {
		init_from();
		dialog.value = false;
	};
	const file_change = async e => {
		const file = e.raw; // 获取 File 对象
		if (!file) return;

		// 创建 FormData 对象
		const formData = new FormData();
		// 将文件添加到 FormData 中，'image' 需和服务器端接收的字段名一致
		formData.append("image", file);

		try {
			// 发送 POST 请求到图片上传接口
			const response = await fetch(`${base_url}/upload-image`, {
				method: "POST",
				body: formData,
			});

			// 检查响应状态
			if (!response.ok) {
				throw new Error(`HTTP error! status: ${response.status}`);
			}

			// 解析响应数据
			const data = await response.json();
			if (data.success) {
				// 上传成功，将图片路径赋值给表单
				form.value.preview_image = data.imagePath;
				msg.msg_success("图片上传成功");
			} else {
				msg.msg_error("图片上传失败");
			}
		} catch (error) {
			msg.msg_error("图片上传失败，请稍后重试");
		}
	};

	const edit_bookmark = book => {
		for (const key in form.value) {
			if (Object.prototype.hasOwnProperty.call(form.value, key)) {
				form.value[key] = book[key];
			}
		}
		edit_id.value = book.id;
		flag.value = false;
		dialog.value = true;
	};
	const delete_bookmark = async id => {
		let res = await service.web.delete_web_by_id(id);
		if (res.code == 200) {
			web_list_all.value = web_list_all.value.filter(item => item.id !== id);
		}
	};
	const bookmark_click = bookmark => {
		console.log(bookmark);
		Events.IPC.Renderer.send("open_new", {
			path: "/open_win",
			name: `open_${new Date().getTime()}`,
			title: bookmark.title,
			is_external_page: true,
			options: {
				width: 1200,
				height: 800,
			},
			src: bookmark.url,
		});
	};
	const add_category = async () => {
		add_category_dialog.value = true;
	};
	const add_category_dialog_sure = async () => {
		if (add_category_form.value.name.length > 8) {
			msg.msg_warning("分类名称不能超过8个字符！");
			return;
		}
		if (!add_category_form.value.name) {
			msg.msg_warning("分类名称不能为空！");
			return;
		}
		let res = await service.web_classify.add_web_classify(
			add_category_form.value.name
		);
		if (res.code == 200) {
			categories.value.push(res.data);
		}
		add_category_form.value.name = "";
		add_category_dialog.value = true;
	};
	const tag_manage = async () => {
		tag_manage_dialog.value = true;
	};
	const add_tag = async () => {
		if (!add_tag_form.value.name) {
			msg.msg_warning("标签名称不能为空！");
			return;
		}
		const res = await service.web_tags.add_web_tag(add_tag_form.value.name);
		if (res.code === 200) {
			add_tag_form.value.name = "";
			tags.value.push(res.data);
		}
	};
	const del_tag = async i => {
		const res = await service.query.delWebTagById(i.id);
		if (res.code == 200) {
			tags.value = tags.value.filter(item => item.id !== i.id);
			const web_res = await service.web.get_web_all()
			web_res.value = web_res.data;
		}
	};
	const edit_tag = async i => {
		ElMessageBox.prompt("请输入新的标签名称！", "标签编辑", {
			confirmButtonText: "确定",
			cancelButtonText: "取消",
			center: true,
		})
			.then(async ({ value }) => {
				if (!value) {
					msg.msg_warning("标签名称不能为空！");
					return;
				}
				const res = await service.web_tags.update_web_tag_by_id(i.id, value);
				if (res.code == 200) {
					tags.value.forEach(item => {
						if (item.id == i.id) {
							item.name = value;
						}
					});
				}
			})
			.catch(() => {});
	};
</script>

<style lang="less" scoped>
	.web_box {
		width: 100%;
		height: 100%;
		box-sizing: border-box;
		display: flex;
		flex-wrap: nowrap;

		.left_console {
			width: 200px;
			height: 100%;
			border-right: var(--split-line);
			box-sizing: border-box;
			flex-shrink: 0;

			.main {
				width: 100%;

				.console {
					width: 100%;
					font-size: 24px;
					height: 44px;
					line-height: 44px;
					text-indent: 10px;
					letter-spacing: 0.5em;
				}

				.main_menu,
				.my_category,
				.common_tags {
					width: 90%;
					margin: 10px auto 0;

					.title {
						width: 100%;
						font-size: 12px;
						font-weight: 600;
						color: var(--global-light-color);
						letter-spacing: 0.5em;
					}

					.list {
						width: 100%;
						margin: 5px 0;
						padding: 0 10px;
						box-sizing: border-box;
						height: 30px;
						line-height: 30px;
						display: flex;
						font-size: 14px;
						justify-content: space-between;
						align-items: center;
						border-radius: 4px;
						cursor: pointer;

						&:hover {
							background-color: rgba(222, 222, 222, 0.3);
						}

						.count {
							width: 3em;
							height: 20px;
							line-height: 20px;
							text-align: center;
							border-radius: 4px;
							background-color: rgb(248, 152.1, 152.1);
							color: white;
						}
					}

					.active {
						background-color: rgb(235.9, 245.3, 255) !important;

						.left {
							color: rgb(121.3, 187.1, 255) !important;
						}
					}

					.tag {
						height: 20px;
						line-height: 20px;
						border-radius: 4px;
						background-color: rgb(248, 152.1, 152.1);
						color: white;
						padding: 0 5px;
						font-size: 12px;
						margin: 4px;
						cursor: pointer;
					}
				}

				.main_menu {
					.list {
						.left {
							.font {
								font-size: 18px;
							}

							.text {
								margin-left: 10px;
							}
						}
					}
				}

				.my_category {
					.title {
						display: flex;
						justify-content: space-between;

						.add {
							color: rgb(121.3, 187.1, 255);
							letter-spacing: 0em;
							cursor: pointer;
						}
					}
				}

				.common_tags {
					display: flex;
					flex-wrap: wrap;
					.title {
						display: flex;
						justify-content: space-between;

						.manage {
							color: rgb(121.3, 187.1, 255);
							letter-spacing: 0em;
							cursor: pointer;
						}
					}
				}
			}
		}

		.right_display {
			flex-grow: 1;

			.main {
				width: 100%;
				min-width: 1200px;
				position: relative;

				.top_navigation {
					width: 100%;
					height: 60px;
					background-color: rgb(255, 255, 255);
					position: sticky;
					top: 0;
					left: 0;
					z-index: 2;
					display: flex;
					align-items: center;
					box-sizing: border-box;
					border-bottom: var(--split-line);

					.search-input {
						width: 300px;
						margin-left: 40px;
					}
					.view-mode-buttons {
						width: 70px;
						height: 32px;
						margin-left: 30px;
						cursor: pointer;
						background-color: white;
						border-radius: 4px;
						.icon_font {
							display: inline-block;
							width: 50%;
							height: 100%;
							font-size: 20px;
							text-align: center;
							line-height: 32px;
							border-radius: 4px;
						}
						.active {
							background-color: #ddd;
						}
					}
					.sort-select {
						width: 150px;
						margin-left: 30px;
					}
					.add {
						padding: 0 15px;
						background-color: #ddd;
						height: 32px;
						line-height: 32px;
						text-align: center;
						border-radius: 4px;
						margin-left: 30px;
						cursor: pointer;
					}
				}

				.details {
					min-width: 1200px;
					max-width: 1200px;
					margin: auto;
					.category {
						font-size: 24px;
						font-weight: 700;
						margin: 20px 0 0 0;
					}
					.amount {
						font-size: 12px;
						color: var(--global-light-color);
					}
				}

				.grid {
					min-width: 1200px;
					max-width: 1200px;
					margin: 20px auto;
					display: grid; // 使用 grid 布局
					grid-template-columns: repeat(3, 1fr); // 定义三列，每列宽度相等
					gap: 20px; // 设置行和列之间的间隙
				}
				.list {
					min-width: 1200px;
					max-width: 1200px;
					margin: 20px auto;
					display: flex;
					justify-content: center;
					flex-wrap: wrap;
					row-gap: 20px;
				}
			}
		}
		.tag_manage_main {
			width: 100%;
			.add_tag {
				width: 100%;
				height: 30px;
				margin-bottom: 10px;
				display: flex;
				justify-content: flex-end;
				.tag_input {
					width: 150px;
					height: 30px;
					box-sizing: border-box;
				}
				.add_tag_cilck {
					width: fit-content;
					height: 30px;
					line-height: 30px;
					margin-left: 10px;
					color: rgb(121.3, 187.1, 255);
					cursor: pointer;
				}
			}
		}
	}
</style>
